package com.hamilton.erik.pt.mobile.android;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.android.volley.Response;
import com.hamilton.erik.pt.core.model.Animal;
import com.hamilton.erik.pt.core.model.Feeding;
import com.hamilton.erik.pt.mobile.android.volley.response.error.listener.DisplayErrorErrorListener;
import com.hamilton.erik.pt.mobile.android.widget.FeedingListAdapter;
import com.hamilton.erik.pt.mobile.client.VolleyJsonRestClient;
import com.hamilton.erik.pt.mobile.util.JsonUtil;
import com.hamilton.erik.pt.mobile.util.ResultUtil;
import com.hamilton.erik.pt.mobile.util.ServerUtil;

public class FeedingListActivity extends ListActivity {

	private Animal animal = null;
	private List<Feeding> feedings = null;
	private ProgressDialog progressDialog = null;
	
	private final int VIEW_FEEDING_ACTIVITY = 0;
	private final int ADD_FEEDING_ACTIVITY = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_feeding_list);

		animal = (Animal)getIntent()
							.getSerializableExtra(
								getString(R.string.extra_animal_object));
		
		if(!TextUtils.isEmpty(animal.getName())) {
			setTitle(animal.getName() + "'s Feedings");
		}

		findViewById(R.id.feeding_list_view_add_feeding_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						add();
					}
				});
		
		createList();
	}
	
	protected void createList() {
		// Note the retrieveFeedings will populate the list on success.
		// This is done because if the retrieve isn't completed by the
		// time the populate is called, we will have a null pointer.
		// We must wait for the retrieval to be successful before continuing.
		if(feedings == null) {
			retrieveList();	
		}
		else {
			populateList();
		}
		
		
		ListView listView = (ListView)findViewById(R.id.feeding_list_view);
		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			  @Override
			  public void onItemClick(AdapterView<?> parent, final View view,
			    int position, long id) {
				  view(parent.getItemAtPosition(position));
			  }
			});
	}
	
	protected void retrieveList() {
		StringBuilder url = new StringBuilder(ServerUtil.getInstance().buildFeedingPath());
		url.append("/retrieve/all/").append(animal.getId());
		
		if (progressDialog == null) {
	        progressDialog = new ProgressDialog(this);
	        progressDialog.setTitle(getString(R.string.progress_loading_title));
	        progressDialog.setMessage(getString(R.string.feeding_list_progress_retrieving_feedings));
	    }
	    progressDialog.show();
		
		VolleyJsonRestClient.getClient().getJsonArray(url.toString(),
								new RetrieveFeedingListSuccessListener(),
								new DisplayErrorErrorListener(this, progressDialog));
	}
	
	protected void populateList() {
		FeedingListAdapter adapter = new FeedingListAdapter(this, feedings);
		
		ListView listView = (ListView)findViewById(R.id.feeding_list_view);
		listView.setAdapter(adapter);
		adapter.notifyDataSetChanged();
	}
	
	protected void add() {
		Feeding feeding = new Feeding();
		feeding.setAnimalId(animal.getId());
		
		Intent editFeedingActivity = new Intent(getApplicationContext(), EditFeedingActivity.class);
		editFeedingActivity.putExtra(getString(R.string.extra_animal_object), animal);
		editFeedingActivity.putExtra(getString(R.string.extra_feeding_object), feeding);
		startActivityForResult(editFeedingActivity, ADD_FEEDING_ACTIVITY);
	}
	
	protected void view(Object object) {

		Feeding selectedFeeding = (Feeding)object;
		
		Intent viewFeedingActivity = new Intent(getApplicationContext(), ViewFeedingActivity.class);
		viewFeedingActivity.putExtra(getString(R.string.extra_animal_object), animal);
		viewFeedingActivity.putExtra(getString(R.string.extra_feeding_object), selectedFeeding);
		startActivityForResult(viewFeedingActivity, VIEW_FEEDING_ACTIVITY);
	}
	
	private class RetrieveFeedingListSuccessListener
							implements Response.Listener<JSONArray> {

		@Override
		public void onResponse(JSONArray response) {
			feedings = new ArrayList<Feeding>();
			if(response != null) {
				try {
					for(int i = 0; i < response.length(); i++) {
						feedings.add(
								JsonUtil.getInstance()
									.getFeeding(response.getJSONObject(i)));
					}
					
					populateList();
					
					if(progressDialog != null && progressDialog.isShowing()) {
						progressDialog.dismiss();
					}
				} catch (Exception e) {
					Log.e("FeedingListActivity",
							String.format("%s: %s","Failed to convert JSONObject to Feeding.", e.getMessage()));
				}
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.feeding_list, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		switch(item.getItemId()) {
			default :
				return super.onOptionsItemSelected(item);
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if(requestCode == VIEW_FEEDING_ACTIVITY &&
			(resultCode == ResultUtil.EDITED ||
			 resultCode == ResultUtil.DELETED)) {
			retrieveList();
			populateList();
		}
		else if(requestCode == ADD_FEEDING_ACTIVITY &&
				resultCode == ResultUtil.RESULT_SUCCESS) {
			retrieveList();
			populateList();
		}
	}

}
